<template>
  <div class="filter-list flex-c">
    <slot name="filterItemLeft"></slot>
    <template v-for="(item, i) in filterList" :key="item.key">
      <div class="filter-item">
        <template v-if="item.type == 'input_keyword'">
          <filterKeyword :currentItem="item" @search="searchKeyword($event, i)" />
        </template>
        <template v-else-if="item.type == 'input_keyword_type'">
          <filterKeywordByType :currentItem="item" @search="searchKeyword($event, i)" />
        </template>
        <template v-else-if="item.type == 'select_multiple'">
          <selectMultiple :key="item.key" :info="item" :defaultVal="item.value" @change="selectMulVal($event, item)" />
        </template>
        <template v-else-if="item.type == 'select'">
          <a-select v-model="item.value" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search :style="{ width: item.width + 'px' }" :placeholder="item.placeholder || item.label" allow-clear :="item.attrs" @change="startSearch">
            <a-option v-for="(option, s) in item.optionItems" :key="s" :value="getOptionVal(item, option, 'value')" :label="getOptionVal(item, option, 'label')" />
          </a-select>
        </template>
        <template v-else-if="item.type == 'input_search'">
          <a-input-search v-model="item.value" :style="{ width: item.width + 'px' }" :placeholder="item.placeholder || item.label" allow-clear @press-enter="startSearch" @clear="startSearch" @search="startSearch" />
        </template>
        <template v-else-if="item.type == 'date_range'">
          <a-range-picker v-model="item.value" :="item.attrs" shortcuts-position="left" :shortcuts="rangeShortcuts(item.attrs ? item.attrs.valueFormat : 'YYYY-MM-DD')" :style="{ width: item.width + 'px' }" @change="startSearch" />
        </template>
        <template v-else-if="item.type == 'date_month'">
          <a-month-picker v-model="item.value" :="item.attrs" :style="{ width: item.width + 'px' }" @change="startSearch" />
        </template>
        <template v-else-if="item.type == 'keyword_date_range'">
          <filterDateRange :data="item" @search="startSearch" />
        </template>
        <template v-else-if="item.type == 'keyword_date_range_custom'">
          <filterDateRangeCustom :data="item" @search="startSearch" />
        </template>
        <template v-else-if="item.type == 'radio_btn'">
          <a-radio-group type="button" v-model="item.value">
            <a-radio v-for="(option, s) in item.optionItems" :key="s" :value="option.value">{{ option.label }}</a-radio>
          </a-radio-group>
        </template>
        <template v-else-if="item.type == 'sel_double'">
          <doubleSel :data="item" @search="doubleSelStartSearch(item)" />
        </template>
        <template v-else-if="item.type == 'cascader'">
          <filterCascader :data="item" @search="startSearch" />
        </template>
        <template v-else-if="item.type == 'cascader1'">
          <filterCascader1 :data="item" @search="startSearch" />
        </template>
        <template v-else-if="item.type == 'num_range'">
          <div class="price-range">
            <div>{{ item.label }}</div>
            <div>
              <a-input-number @blur="startSearch" hide-button v-model="item.min" allow-clear style="width: 80px" />
            </div>
            <div>
              <a-input-number @blur="startSearch" hide-button v-model="item.max" allow-clear style="width: 80px" />
            </div>
          </div>
        </template>
        <template v-else-if="item.type == 'num_range_type'">
          <div style="display: flex">
            <div>
              <a-select v-model="item.value" :trigger-props="{ autoFitPopupMinWidth: true }" :style="{ width: item.width + 'px' }" :placeholder="item.placeholder || item.label" :="item.attrs" @change="startSearch">
                <a-option v-for="(option, s) in item.optionItems" :key="s" :value="getOptionVal(item, option, 'value')" :label="getOptionVal(item, option, 'label')" />
              </a-select>
            </div>
            <div>
              <a-input-number @blur="startSearch" hide-button v-model="item.min" allow-clear style="width: 80px" />
            </div>
            <div>
              <a-input-number @blur="startSearch" hide-button v-model="item.max" allow-clear style="width: 80px" />
            </div>
          </div>
        </template>
      </div>
    </template>
    <!-- 气泡 -->
    <a-popover v-if="filterListSub.length" trigger="click" ref="selectMulRef" position="bottom" @popup-visible-change="popupVisibleChange">
      <template #content>
        <template v-for="(item, i) in filterListSub" :key="item.key">
          <div class="filter-item">
            <template v-if="item.type == 'input_keyword'">
              <filterKeyword :currentItem="item" @search="searchKeywordSub($event, i)" />
            </template>
            <template v-else-if="item.type == 'select_multiple'">
              <selectMultiple :key="item.key" :info="item" :defaultVal="item.value" @change="selectMulValSub($event, item)" />
            </template>
            <template v-else-if="item.type == 'select'">
              <a-select v-model="item.value" :trigger-props="{ autoFitPopupMinWidth: true }" allow-search :style="{ width: item.width + 'px' }" :placeholder="item.placeholder || item.label" allow-clear :="item.attrs">
                <a-option v-for="(option, s) in item.optionItems" :key="s" :value="getOptionVal(item, option, 'value')" :label="getOptionVal(item, option, 'label')" />
              </a-select>
            </template>
            <template v-else-if="item.type == 'input_search'">
              <a-input-search v-model="item.value" :style="{ width: item.width + 'px' }" :placeholder="item.placeholder || item.label" allow-clear />
            </template>
            <template v-else-if="item.type == 'date_range'">
              <a-range-picker v-model="item.value" :="item.attrs" shortcuts-position="left" :shortcuts="rangeShortcuts(item.attrs ? item.attrs.valueFormat : 'YYYY-MM-DD')" :style="{ width: item.width + 'px' }" />
            </template>
            <template v-else-if="item.type == 'date_month'">
              <a-month-picker v-model="item.value" :="item.attrs" :style="{ width: item.width + 'px' }" />
            </template>
            <template v-else-if="item.type == 'keyword_date_range'">
              <filterDateRange :data="item" />
            </template>
            <template v-else-if="item.type == 'keyword_date_range_custom'">
              <filterDateRangeCustom :data="item" />
            </template>
            <template v-else-if="item.type == 'radio_btn'">
              <a-radio-group type="button" v-model="item.value">
                <a-radio v-for="(option, s) in item.optionItems" :key="s" :value="option.value">{{ option.label }}</a-radio>
              </a-radio-group>
            </template>
            <template v-else-if="item.type == 'sel_double'">
              <doubleSel :data="item" @search="doubleSelStartSearchSub(item)" />
            </template>
            <template v-else-if="item.type == 'cascader'">
              <filterCascader :data="item" />
            </template>
            <template v-else-if="item.type == 'cascader1'">
              <filterCascader1 :data="item" />
            </template>
            <template v-else-if="item.type == 'num_range'">
              <div class="price-range">
                <div>{{ item.label }}</div>
                <div>
                  <a-input-number hide-button v-model="item.min" allow-clear style="width: 80px" />
                </div>
                <div>
                  <a-input-number hide-button v-model="item.max" allow-clear style="width: 80px" />
                </div>
              </div>
            </template>
            <template v-else-if="item.type == 'num_range_type'">
              <div style="display: flex">
                <div>
                  <a-select v-model="item.value" :trigger-props="{ autoFitPopupMinWidth: true }" :style="{ width: item.width + 'px' }" :placeholder="item.placeholder || item.label" :="item.attrs">
                    <a-option v-for="(option, s) in item.optionItems" :key="s" :value="getOptionVal(item, option, 'value')" :label="getOptionVal(item, option, 'label')" />
                  </a-select>
                </div>
                <div>
                  <a-input-number hide-button v-model="item.min" allow-clear style="width: 80px" />
                </div>
                <div>
                  <a-input-number hide-button v-model="item.max" allow-clear style="width: 80px" />
                </div>
              </div>
            </template>
          </div>
        </template>
        <div class="flex-c-end" style="margin-top: 20px">
          <a-space>
            <a-button size="small" @click="clearPopover">清除</a-button>
            <a-button type="primary" size="small" @click="setPopoverFilter">确认</a-button>
          </a-space>
        </div>
      </template>
      <a-button class="gray-outline filter-item">
        <template #icon>
          <icon-filter />
          <span class="red-dot" v-show="hasFilterVal"></span>
        </template>
      </a-button>
    </a-popover>
    <div class="filter-item" v-if="isReset">
      <a-button @click="resetAll">重置</a-button>
    </div>
    <slot name="filterItemRight"></slot>
    <div class="filter-item" v-if="isSearch">
      <a-button type="primary" @click="startSearch">搜索</a-button>
    </div>
  </div>
  <!-- <div class="filter-result" v-if="resultTags.length > 0 && isShowTag">
    <a-space wrap>
      <a-tag v-for="item in resultTags" size="small" color="arcoblue" :closable="!item.undeletable" :key="item.key" @close="delTag(item)">
        <template v-if="!(item.tagVal instanceof Array && item.tagVal.length > 2)">
          <span> {{ item.label }}：</span>
          <p v-if="item.type != 'num_range' && item.type != 'num_range_type'">{{ item.tagVal instanceof Array ? item.tagVal?.join(',') : item.tagVal }}</p>
          <p v-else>{{ item.tagVal instanceof Array ? item.tagVal?.join('~') : item.tagVal }}</p>
        </template>
        <a-popover v-else position="bottom">
          <div class="flex-c">
            <span> {{ item.label }}：</span>
            <p>{{ item.tagVal[0] }}，{{ item.tagVal[1] }}等{{ item.tagVal.length }}项</p>
          </div>
          <template #content>
            <p v-for="(val, j) in item.tagVal" :key="j">{{ val }}</p>
          </template>
        </a-popover>
      </a-tag>
      <a-button type="text" style="color: #000430" v-if="resultTags.length > 1" size="mini" @click="clearAll">清除全部</a-button>
    </a-space>
  </div> -->
</template>
<script setup lang="ts">
  import { defineComponent, PropType, reactive, ref, watchEffect } from 'vue'
  import { FilterTableItem } from '@/types/components'
  import filterKeyword from '@/components/Form/filterKeyword.vue'
  import filterKeywordByType from '@/components/Form/filterKeywordByType.vue'
  import filterDateRange from './Form/filterDateRange.vue'
  import filterDateRangeCustom from './Form/filterDateRangeCustom.vue'
  import selectMultiple from './Form/selectMultiple.vue'
  import filterCascader from './Form/filterCascader.vue'
  import filterCascader1 from './Form/filterCascader1.vue'
  import doubleSel from './Form/doubleSel.vue'
  // import { treeFindPath } from '@/utils/index'
  // import dayjs from 'dayjs'
  import { cloneDeep } from 'lodash-es'
  import { rangeShortcuts } from '@/utils/timeFormat'
  const props = defineProps({
    filterItem: {
      type: Array as PropType<FilterTableItem[]>,
      default: () => [],
    },
    isReset: Boolean,
    maxNum: {
      type: Number,
      default: 0,
    },
    isShowTag: {
      type: Boolean,
      default: true,
    },
    isSearch: {
      type: Boolean,
      default: false,
    },
  })

  interface keyOptionType {
    label: string
    value: string
  }

  const emit = defineEmits(['search'])
  // const originFilterList = toRef(props, 'filterItem')
  // 查询的参数
  let searchParam: any = {}
  // let resultTags = ref<any>([])
  const filterList = reactive<FilterTableItem[]>([])
  const filterListSub = reactive<FilterTableItem[]>([])
  const selectMulRef = ref()
  const hasFilterVal = ref(false)

  // 是否有查询条件
  const setHasFilterVal = () => {
    hasFilterVal.value = false
    filterListSub.forEach((el: any) => {
      // 数值范围
      if (el.type == 'num_range' || el.type == 'num_range_type') {
        let val = searchParam[el?.optionField?.['min'] || 'min'] || searchParam[el?.optionField?.['max'] || 'max']
        if (val || val === 0) {
          hasFilterVal.value = true
        }
      } else if (el.type == 'keyword_date_range' && searchParam.startDate) {
        hasFilterVal.value = true
      } else if (el.type == 'input_keyword_type' && searchParam.keyword) {
        hasFilterVal.value = true
      } else if (searchParam[el.key]?.length) {
        hasFilterVal.value = true
      }
    })
  }

  //关键字类型实时查询
  const searchKeyword = (searchVal: any, i: number) => {
    filterList[i].key = searchVal.code
    filterList[i].label = searchVal.label
    filterList[i].value = searchVal.value
    filterList[i].searchType = searchVal.searchType
    startSearch()
  }
  // 批量选择数据实时查询
  const selectMulVal = (searchVal: any, item: any) => {
    item.value = searchVal
    startSearch()
  }
  const doubleSelStartSearch = (item: any) => {
    item.keyItems.forEach((e: keyOptionType) => {
      delete searchParam[e.value]
    })
    startSearch()
  }
  //关键字类型popover查询
  const searchKeywordSub = (searchVal: any, i: number) => {
    filterListSub[i].key = searchVal.code
    filterListSub[i].label = searchVal.label
    filterListSub[i].value = searchVal.value
    filterListSub[i].searchType = searchVal.searchType
  }
  // 批量选择数据popover查询
  const selectMulValSub = (searchVal: any, item: any) => {
    item.value = searchVal
  }
  const doubleSelStartSearchSub = (item: any) => {
    item.keyItems.forEach((e: keyOptionType) => {
      delete searchParam[e.value]
    })
  }

  const startSearch = () => {
    // 如果有筛选收起气泡窗口，则隐藏
    if (selectMulRef.value) {
      selectMulRef.value.handlePopupVisibleChange(false)
    }
    // setResultTags()
    searchParam = {}
    let _list = [...filterList, ...filterListSub]
    _list.forEach((el: FilterTableItem) => {
      if (el.type === 'keyword_date_range') {
        //多类型时间筛选
        searchParam.dataType = el.key
        searchParam.startDate = el.value instanceof Array ? el.value[0] : ''
        searchParam.endDate = el.value instanceof Array ? el.value[1] : ''
      } else if (el.type === 'input_keyword_type') {
        //关键词精确模糊
        searchParam.searchType = el?.searchType
        searchParam.keyword = el.value
        searchParam.keywordType = el.key
      } else if (el.type === 'num_range_type' || el.type === 'num_range') {
        // 多类型价格区间筛选
        searchParam[el.key] = el.value
        searchParam[el?.optionField?.['min'] || 'min'] = el.min
        searchParam[el?.optionField?.['max'] || 'max'] = el.max
      } else {
        searchParam[el.key] = el.value instanceof Array && el.type != 'date_range' ? el.value.join(',') : el.value
      }
    })
    if (!searchParam.startDate) {
      searchParam.dataType = ''
    }
    setHasFilterVal()
    emit('search', searchParam)
  }
  const resetAll = () => {
    handleFilterList(props.filterItem)
    startSearch()
  }
  const getOptionVal = (el: FilterTableItem, option: any, key: string) => {
    let _key = (el.optionField?.[key] || key) as string
    return option[_key]
  }
  // 为了不更改每个页面的JSON数据，在原有的基础上根据maxNum拆分2部分数据
  // filterList为默认显示的数据，实时查询
  // filterListSub为收起的数据，点击确认按钮查询
  const handleFilterList = (list: Array<FilterTableItem>) => {
    let _list = cloneDeep(props.filterItem)
    filterList.length = 0
    filterListSub.length = 0
    if (props.maxNum > 0) {
      let arr1 = _list.slice(0, props.maxNum)
      let arr2 = _list.slice(props.maxNum, _list.length)
      filterList.push(...arr1)
      filterListSub.push(...arr2)
    } else {
      filterList.push(..._list)
    }
  }
  // 用于下拉选项是异步数据的情况
  // 不改变页面传参的情况下，根据是maxNum来判断更新filterList或filterListSub
  const changeOptions = (index: number, list: Array<any>) => {
    if (props.maxNum && props.maxNum >= index) {
      filterListSub[index - props.maxNum].optionItems = list
    } else {
      filterList[index].optionItems = list
    }
  }
  // 取消Popup查询
  const closePopover = () => {
    selectMulRef.value.handlePopupVisibleChange(false)
  }
  // 清除
  const clearPopover = () => {
    filterListSub.length = 0
    let _list = cloneDeep(props.filterItem)
    let arr2 = _list.slice(props.maxNum, _list.length)
    filterListSub.push(...arr2)
    startSearch()
    closePopover()
  }
  // 打开Popup面板重置显示当前查询条件
  const popupVisibleChange = (status: boolean) => {
    if (status) {
      filterListSub.forEach((el: any, i: number) => {
        // let _data = props.filterItem.find((item: any) => item.key == el.key)
        let _data = props.filterItem[props.maxNum + i]
        let val = searchParam[el.key] || _data?.value
        if (el.type == 'num_range_type' || el.type === 'num_range') {
          el.value = val
          el.min = searchParam[el?.optionField?.['min'] || 'min']
          el.max = searchParam[el?.optionField?.['max'] || 'max']
        } else if (el.type == 'keyword_date_range') {
          el.key = searchParam.dataType || _data?.key
          el.value = searchParam.startDate ? [searchParam.startDate, searchParam.endDate] : _data?.value
        } else if (el.type == 'keyword_date_range_custom') {
          el.value = searchParam[el.key] ? searchParam[el.key].split(',') : _data?.value
        } else if (el.type == 'input_keyword_type') {
          el.searchType = searchParam.searchType || _data?.searchType
          el.value = searchParam.keyword || _data?.value
          el.keywordType = searchParam.keywordType || _data?.key
        } else {
          el.value = val
        }
      })
    }
  }
  function setPopoverFilter() {
    startSearch()
    closePopover()
  }

  watchEffect(() => {
    handleFilterList(props.filterItem)
  })
  defineExpose({ changeOptions })
  // 获取查过结果显示的值
  // const getTagVal = (item: FilterTableItem) => {
  //   //时间范围
  //   if ((item.type == 'date_range' || item.type == 'keyword_date_range') && item.value instanceof Array) {
  //     return item?.value?.map((str) => dayjs(str).format('YYYY-MM-DD'))?.join('~')
  //   }
  //   if (item.value instanceof Array) {
  //     return item.value.map((str: string) => {
  //       return enumVal(item.optionItems, item.optionField, str)
  //     })
  //   } else {
  //     return enumVal(item.optionItems, item.optionField, item.value)
  //   }
  // }
  // const getCascaderName = (el: any) => {
  //   console.log(el)
  //   let valKey = el?.attrs?.fieldNames?.value || 'id'
  //   let nameKey = el?.attrs?.fieldNames?.label || 'name'
  //   let arr: Array<string> = []
  //   if (el.value instanceof Array) {
  //     el.value.forEach((e: string) => {
  //       let arr1 = treeFindPath(el.optionItems, (data: any) => data[valKey] == e)
  //       arr.push(arr1[arr1.length - 1].name)
  //     })
  //   } else {
  //     let arr1 = treeFindPath(el.optionItems, (data: any) => data[valKey] == el.value)
  //     arr.push(arr1[arr1.length - 1][nameKey])
  //   }
  //   return arr
  // }

  // const setResultTags = () => {
  //   resultTags.value = []
  //   let arr: any = []
  //   filterList.forEach((el: FilterTableItem) => {
  //     let val: any = el.value
  //     let noVal = val === '' || val === null || val === undefined || (val instanceof Array && val.length === 0)

  //     if (!noVal && !el.isClear) {
  //       arr.push({
  //         ...el,
  //         tagVal: ['cascader', 'cascader1'].includes(el.type) ? getCascaderName(el) : getTagVal(el),
  //       })
  //     }
  //   })
  //   nextTick(() => {
  //     resultTags.value = arr
  //   })
  // }

  // const delTag = (data: any) => {
  //   let index = filterList.findIndex((el: FilterTableItem) => el.key == data.key)
  //   filterList[index].value = props.filterItem[index].undeletable ? props.filterItem[index].value : null
  //   startSearch()
  // }

  // const clearAll = () => {
  //   filterList.forEach((el: FilterTableItem, index: number) => {
  //     el.value = props.filterItem[index].undeletable ? props.filterItem[index].value : null
  //   })

  //   startSearch()
  // }

  // const enumVal = (optionItems: any, optionField: any, str: any) => {
  //   if (!optionItems?.length) return str
  //   let valKey = optionField?.value || 'value'
  //   let labelKey = optionField?.label || 'label'
  //   let option = optionItems?.find((e: any) => str == e[valKey])
  //   return option?.[labelKey] || str
  // }

  // onMounted(() => {
  //   setResultTags()
  // })
</script>
<script lang="ts">
  export default defineComponent({
    name: 'TableFilter',
  })
</script>

<style lang="less" scoped>
  .filter-item {
    margin-right: 8px;
    margin-bottom: 5px;
  }
  :deep(.arco-radio-group-button) {
    padding: 0;
    .arco-radio-button {
      margin: 0;
      background-color: #fff;
      line-height: 30px;
      border: 1px solid var(--color-border);
      &:first-child {
        border-radius: 5px 0 0 5px;
      }
      &:last-child {
        border-radius: 0 5px 5px 0;
      }
    }
    .arco-radio-checked {
      border-color: rgb(var(--primary-6));
    }
  }

  .filter-result {
    margin-bottom: 5px;
  }
  .filter-list {
    flex-wrap: wrap;
  }

  .price-range {
    display: flex;
    height: 32px;
    line-height: 32px;
    overflow: hidden;
    :deep(.arco-input-number-size-medium) {
      border: none;
    }
    border: 1px solid #dadde2;
    border-radius: 3px;
    div {
      &:nth-child(1) {
        padding: 0 8px;
        box-sizing: border-box;
        border-right: 1px solid #dadde2;
      }
      &:nth-child(2) {
        border-right: 1px solid #dadde2;
      }
    }
  }
  .red-dot {
    position: absolute;
    width: 8px;
    height: 8px;
    background-color: red;
    border-radius: 50%;
    top: 0;
    right: 0;
  }
</style>
